<!--
@description ：访客雷达
-->

<template>
  <div class="app-container">
    <el-row class="row-radar">
      <el-col :span="4">
        <div class="mt-20">
          <el-tree ref="tree" v-loading="treeLoading" :data="treeData" :expand-on-click-node="false" :props="treeProps"
                   default-expand-all highlight-current @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node">
              <el-tooltip v-if="node.label.length > 8" :content="node.label" effect="dark" placement="bottom">
                <span class="label-info">{{ node.label }}</span>
              </el-tooltip>
              <span v-else>{{ node.label }}</span>
              <el-dropdown v-if="data.id" trigger="click">
                <i class="el-icon-more" @click.stop></i>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item style="color: #082aff" @click.native="itemEdit(node, data)">修改名称
                  </el-dropdown-item>
                  <el-dropdown-item style="color: #082aff" @click.native="itemDel(node, data)" :disabled="!data.delFlag">删除分组
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="data.sortId == '1'" style="color: #082aff"
                                    @click.native="itemSortEdit(node, data, 'up')">上移
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="data.sortId == groupTotal" style="color: #082aff"
                                    @click.native="itemSortEdit(node, data, 'down')">下移
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="data.sortId == '1'" style="color: #082aff"
                                    @click.native="itemSortEdit(node, data,'top')">置顶
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="data.sortId == groupTotal" style="color: #082aff"
                                    @click.native="itemSortEdit(node, data,'bot')">置底
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
              <span v-if="!data.id" class="add" style="color: #082aff" @click="handleAddItem">
                <i class="el-icon-circle-plus-outline"></i>&nbsp;添加
              </span>
            </div>
          </el-tree>
        </div>
      </el-col>
      <el-col :span="20" style="border-left: 1px solid #eee; padding: 16px 15px 20px 15px;">
        <div style="border-bottom: 1px solid #eee">
          <NormalForm :enumOpt="enumOpt" :formList="formList" :isShowCard="false" :operateForm="queryForm"
                      pageTitle="访客雷达"
                      @handleQuery="handleQuery" @handleReset="handleReset"></NormalForm>
        </div>
        <div style="text-align: right; margin: 20px 0;">
          <el-button icon="el-icon-plus" type="primary"
                     @click="$router.push({path: 'createVisitorRadar', query: {flag: '1'}})">新增访客雷达
          </el-button>
        </div>
        <div>
          <el-table v-loading="loading" :data="tableList" max-height="560" min-height="420" style="width: 100%">
            <el-table-column :show-overflow-tooltip="true" align="center" label="名称" min-width="160"
                             prop="radarName"></el-table-column>
            <el-table-column :show-overflow-tooltip="false" align="center" label="类型" min-width="120"
                             prop="mediaType">
              <template slot-scope="scope">
                {{ fileType[+scope.row.mediaType] }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="客户标签" min-width="160"
                             prop="customerTag">
              <template slot-scope="scope">
                <tagGroupShowTable :tagGroup="scope.row.customerTag"/>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="false" align="center" label="总访问人数" min-width="120"
                             prop="viewAllCount">
              <template slot="header">
                <div>总访问人数
                  <el-tooltip
                    content="统计该雷达下所有的UV，去重"
                    effect="dark" placement="top">
                    <i class="el-icon-info" style="margin-left: 4px;color: #CCCCCC"></i></el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="false" align="center" label="总发送次数" min-width="120"
                             prop="sendAllCount">
              <template slot="header">
                <div>总发送次数
                  <el-tooltip
                    content="统计发送次数和转发次数"
                    effect="dark" placement="top">
                    <i class="el-icon-info" style="margin-left: 4px;color: #CCCCCC"></i></el-tooltip>
                </div>
              </template>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="false" align="center" label="创建人" min-width="120"
                             prop="createUser"></el-table-column>
            <el-table-column :show-overflow-tooltip="false" align="center" label="雷达状态" min-width="100"
                             prop="useFlag">
              <slot slot-scope="scope">
                <el-tag v-if="scope.row.useFlag == '1'" type="success">启用中</el-tag>
                <el-tag v-if="scope.row.useFlag == '0'" type="error">已停用</el-tag>
              </slot>
            </el-table-column>
            <el-table-column :show-overflow-tooltip="false" align="center" label="创建时间" min-width="160"
                             prop="createTime"></el-table-column>
            <el-table-column align="center" class-name="small-padding fixed-width" fixed="right" label="操作"
                             width="260">
              <template slot-scope="{ row }">
                <div style="display: flex; justify-content: space-around">
                  <el-button size="mini" type="text" @click="editState(row)">
                    {{ row.useFlag == '0' ? '启用' : row.useFlag == '1' ? '停用' : '' }}
                  </el-button>
                  <el-button size="mini" type="text"
                             @click="$router.push({path: 'createVisitorRadar', query: {flag: '2', id: row.radarId}})">编辑
                  </el-button>
                  <el-button size="mini" type="text" @click="deleteItem(row)">删除
                  </el-button>
                  <el-button :data-clipboard-text="row.shortMaterialUrl ? shortLinkQ + row.shortMaterialUrl :  longLinkQ + row.radarUrl" class="tag-copy" size="mini" type="text"
                             @click="shareRoute">复制链接
                  </el-button>
                  <el-button size="mini" type="text"
                             @click="$router.push({path: 'visitorRadarDataAnalyze', query: {id: row.radarId}})">数据分析
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <NormalPagination :currentPage="queryForm.pageNum" :pageSize="queryForm.pageSize" :total="total"
                            @handleCurrentChange="getListFn"
                            @handleSizeChange="getListFn"></NormalPagination>
        </div>
      </el-col>
    </el-row>
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               :title="treeForm.id ? '编辑' : '添加' + '分组'"
               :visible.sync="treeDialogVisible" width="400px">
      <el-form ref="treeForm" :model="treeForm" label-width="120px">
        <el-form-item label="请输入分组名称">
          <el-input v-model="treeForm.name" maxlength="32" placeholder="请输入" show-word-limit></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button plain type="info" @click="treeDialogVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="treeSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除分组 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               :visible.sync="delVisible"
               title="删除分组确认" width="400px">
      <span>确认删除该分组吗？</span>
      <div slot="footer">
        <el-button plain type="info" @click="delVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="treeDelSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除分组 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false"
               :visible.sync="delToReVisible" append-to-body
               title="移动分组" width="460px">
      <div class="delToRe_info">
        <i class="el-icon-warning" style="color: #082aff;margin-right: 6px"></i>
        <span>{{ `该分组共有${delGroupTotal}条数据，请移入其他分组` }}</span>
      </div>
      <el-form ref="delToReForm" :model="delToReForm" :rules="delToReRules" label-width="160px">
        <el-form-item label="请选择要移入的分组:" prop="newId">
          <el-select v-model="delToReForm.newId" clearable placeholder="请选择分组">
            <el-option v-for="item in newGroupList" :key="item.id"
                       :label="item.name" :value="item.id"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button plain type="info" @click="delToReVisible = false">取 消
        </el-button>
        <el-button type="primary" @click="treeDelToReSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除table数据 -->
    <el-dialog :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="delTable" title="删除"
               width="400px">
      <span>确认删除该条数据吗？</span>
      <div slot="footer">
        <el-button type="info" @click="delTable = false">取 消</el-button>
        <el-button type="primary" @click="toSureDel">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import {categoryAddCorp, categoryDelCorp, categoryEditCorp, categoryList} from "@/api/article/group";
import {
  changeRadarUseFlag,
  delRadarCategory, delRadarInfo,
  queryRadarCount,
  queryRadarInfoList,
  queryUserList,
  sortRadarCategory
} from '@/api/visitorRadar/index'

export default {
  name: "visitorRadar", //访客雷达
  props: {},
  components: {},
  data() {
    return {
      treeForm: {
        id: '',
        name: '',
      },
      treeData: [
        {
          id: '',
          name: '全部',
          parentId: 0,
          hasParent: false,
          hasChildren: true,
          children: []
        },
      ],
      treeProps: {
        children: 'children',
        label: 'name'
      },
      groupTotal: 0, //分组数据总数
      queryForm: {
        weUserId: [],//执行员工
        radarName: '',//雷达名称
        useFlag: '', //雷达状态
        pageNum: 1,
        pageSize: 10,
      }, // 查询问卷
      formList: [
        {
          label: '员工',
          value: [],
          prop: 'weUserId',
          type: 'CASCADER',
          emunName: 'weUserIdList',
          multiple: false,
        },
        {
          label: '雷达名称',
          value: '',
          prop: 'radarName',
          type: 'INPUT',
          emunName: ''
        },
        {
          label: '雷达状态',
          value: '',
          prop: 'useFlag',
          type: 'SELECT',
          emunName: 'radarStatesList'
        },
      ], // 查询框
      enumOpt: {
        weUserIdList: [],
        radarStatesList: [
          {dictLabel: '开启', dictValue: '1'},
          {dictLabel: '关闭', dictValue: '0'},
        ],
      },
      tableList: [], // 表格数据
      total: 0, //表格数据总数
      loading: false,
      treeDialogVisible: false, // 新增/编辑分组
      delVisible: false, // 分组删除确认
      delTable: false, // 表格删除确认
      treeLoading: false,
      delToReVisible: false, //移动分组弹窗
      delToReForm: {
        newId: '',
      },
      newGroupList: [], // 移动分组的数据
      delToReRules: {
        newId: {
          required: true, message: '要移入的分组不能为空', trigger: 'change'
        },
      },
      delGroupTotal: 0,
      currentGroupId: '',
      currentRow: null,
      fileType: {
        11: 'h5链接',
        5: '海报',
        3: '文件',
        4: '文章',
        99: '险种',
        7: '多媒体',
        8: '本地上传',
        9: '',
        10: '问卷',
        66: '小程序',
        100: '本地上传文件',
      },
      shortLinkQ: window.globalConfig.SHARE_SHORT_LINK,
      longLinkQ: window.globalConfig.SHARE_URL + '/'
    }
  },
  watch: {},
  methods: {
    // 获取分组数据
    getNodeFn() {
      let params = {
        levelType: '0',
        mediaType: '12',
      }
      categoryList(params).then(res => {
        if (res.code == 200) {
          this.groupTotal = res.data ? res.data.length : 0
          this.$set(this.treeData[0], 'children', res.data)
        }
      })
    },
    // 分组点击事件
    handleNodeClick(data) {
      console.log(data, '分组排序事件')
      this.queryForm.groupId = data.id
      this.currentGroupId = data.id
      this.getListFn()
    },
    // 编辑分组
    itemEdit(node, data) {
      console.log(node, data, '修改分组')
      this.treeForm = data
      this.treeDialogVisible = true
    },
    // 删除分组
    itemDel(node, data) {
      if(!data.delFlag) return
      console.log(node, data, '删除分组')
      this.treeForm = data
      this.delVisible = true
    },
    // 新增/修改分组提交
    treeSubmit() {
      this.$refs.treeForm.validate(async (valid) => {
        if (valid) {
          const params = {
            id: this.treeForm.id || null,
            levelType: '0',
            mediaType: '12',
            name: this.treeForm.name
          }
          if (this.treeForm.id) {
            categoryEditCorp(params).then(res => {
              this.treeDialogVisible = false
              this.$message.success('分组编辑成功')
              this.getNodeFn()
            })
          } else {
            categoryAddCorp(params).then(res => {
              this.treeDialogVisible = false
              this.$message.success('分组添加成功')
              this.getNodeFn()
            })
          }
        } else {
          return false
        }
      })
    },
    // 数组排序修改
    itemSortEdit(node, data, flag) {
      console.log(flag, 'flag')
      let arr = JSON.parse(JSON.stringify(this.treeData[0].children))
      if (flag == 'up') {
        // 上移
        // 定义要交换位置的对象索引
        let index1 = +data.sortId - 1;
        let index2 = +data.sortId - 2;
        // 交换位置
        let temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
        console.log(arr, '上移', index1, index2)
      } else if (flag == 'down') {
        // 下移
        // 定义要交换位置的对象索引
        let index1 = +data.sortId - 1;
        let index2 = +data.sortId;
        // 交换位置
        let temp = arr[index1];
        arr[index1] = arr[index2];
        arr[index2] = temp;
        console.log(arr, '下移', index1, index2)
      } else if (flag == 'top') {
        // 置顶
        // 将元素移动到最前面
        let index = +data.sortId - 1;
        let element = arr.splice(index, 1)[0]; // 先将元素从数组中删除并保存到变量中
        arr.unshift(element); // 再将元素插入到数组的最前面
        console.log(arr, '置顶')
      } else if (flag == 'bot') {
        // 置底
        // 将元素移动到最后面
        let index = +data.sortId - 1;
        let element = arr.splice(index, 1)[0]; // 先将元素从数组中删除并保存到变量中
        arr.push(element); // 再将元素插入到数组的最后面
        console.log(arr, '置底')
      }
      arr.forEach((item, ind) => {
        item.sortId = String(ind + 1)
      })
      const idList = arr.map(item => item.id)
      this.treeLoading = true
      sortRadarCategory({idList: idList}).then(res => {
        if (res.code == 200) this.getNodeFn()
        this.treeLoading = false
      }).catch(() => {
        this.treeLoading = false
      })
    },
    // 删除分组提交
    treeDelSubmit() {
      queryRadarCount({id: this.treeForm.id}).then(res => {
        if (res.code == 200) {
          if (res.data.delFlag == true) {
            categoryDelCorp(this.treeForm.id).then(res => {
              if (res.code == 200) {
                this.$message.success('删除成功')
                this.getNodeFn()
                this.delVisible = false
              }
            })
          } else {
            this.delGroupTotal = res.data.radarCount || 0
            this.currentGroupId = this.treeForm.id
            this.delToReVisible = true
            this.$refs.delToReForm.resetFields()
            this.newGroupList = this.treeData[0]?.children.filter(item => item.id != this.treeForm.id)
            this.delToReForm.newId = this.newGroupList ? this.newGroupList[0]?.id : ''

          }
        }
      })
    },
    // 添加分组
    handleAddItem() {
      this.treeForm = {
        id: '',
        name: '',
      }
      this.treeDialogVisible = true
    },
    // 筛选
    handleQuery() {
      this.queryForm.pageNum = 1
      this.getListFn()
    },
    // 查询
    getListFn() {
      let params = {
        weUserId: this.queryForm.weUserId ? this.queryForm.weUserId[this.queryForm.weUserId.length - 1] : '',
        radarName: this.queryForm.radarName || '',//雷达名称
        useFlag: this.queryForm.useFlag || '', //雷达状态
        categoryId: this.currentGroupId || '', //分组id
        pageNum: this.queryForm.pageNum,
        pageSize: this.queryForm.pageSize,
      }
      this.loading = true
      queryRadarInfoList(params).then(res => {
        if (res.code == 200) {
          this.tableList = res.rows.map(item => {
            return {
              ...item,
              customerTag: item.customerTag ? JSON.parse(item.customerTag) : [],
            }
          })
          this.total = res.total
          this.$set(this, 'tableList', this.tableList)
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 重置
    handleReset() {
      this.queryForm = {
        weUserId: [],
        radarName: '',
        useFlag: '',
        pageNum: 1,
        pageSize: 10,
      }
      this.currentGroupId = ''
      this.getNodeFn()
      this.getListFn()
    },
    // 雷达状态修改
    editState(row) {
      let params = {
        radarId: row.radarId,
        useFlag: row.useFlag == '1' ? '0' : '1'
      }
      changeRadarUseFlag(params).then(res => {
        if (res.code == 200) {
          this.$message.success(row.useFlag == '0' ? '启用成功' : '停用成功')
          this.handleQuery()
        }
      })
    },
    // 删除
    deleteItem(row) {
      this.delTable = true
      this.currentRow = { ...row }
    },
    // 删除确认
    toSureDel(){
      delRadarInfo({radarId: this.currentRow.radarId,}).then(res => {
        if (res.code == 200) {
          this.$message.success('删除成功')
          this.delTable = false
          this.handleQuery()
        }
      })
    },
    // 复制链接
    shareRoute() {
      let clipboard = new this.clipboard('.tag-copy')
      clipboard.on('success', (e) => {
        this.$message({
          message: '复制链接成功!',
          type: 'success',
          duration: 2000
        })
        //清除选中
        e.clearSelection()
        //释放内存，以防重复复制
        clipboard.destroy()
      })
      clipboard.on('error', (e) => {
        // 不支持复制
        this.$message({
          message: '复制链接失败!',
          type: 'error',
          duration: 2000
        })
        //清除选中
        e.clearSelection()
        //释放内存，以防重复复制
        clipboard.destroy()
      })
    },
    // 移动分组
    treeDelToReSubmit() {
      this.$refs.delToReForm.validate((valid) => {
        if (valid) {
          let params = {
            id: this.currentGroupId,
            newId: this.delToReForm.newId
          }
          delRadarCategory(params).then(res => {
            if (res.code == 200) {
              this.$message.success('分组迁移成功')
              this.currentGroupId = ''
              this.delToReVisible = false
              this.delVisible = false
              this.getNodeFn()
              this.getListFn()
            }
          })
        }
      })
    },
  },
  mounted() {
    queryUserList().then(res => {
      this.enumOpt.weUserIdList = res.rows && res.rows.length > 0 ? res.rows.map(item => {
        return {
          value: item.deptId,
          label: item.deptName,
          children: item.userList ? item.userList.map(itm => {
            return {value: itm.userId, label: itm.userName}
          }) : null
        }
      }) : []
    })
    this.getNodeFn()
    this.handleQuery()
  },
  created() {
  },
}

</script>

<style lang="scss" scoped>

::v-deep.app-container {
  height: 100%;
  padding: 0;
}

.row-radar {
  background: #fff;
  height: 100%;
  border-radius: 8px;

  ::v-deep {
    .el-tabs__header {
      margin: 0;
    }

    .el-tree {
      padding: 10px 10px 0 10px;
    }

    .el-tree-node__content {
      height: 35px;
      padding-left: 10px !important;
    }
  }
}

.custom-tree-node {
  width: 100%;
  display: flex;
  justify-content: space-between;
  padding-right: 10px;
  font-size: 12px;

  .label-info {
    width: 100px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
  }
}

::v-deep.el-tag.el-tag--success {
  background-color: #e6f9ef !important;
  border-color: #cdf3df !important;
  color: #06c160 !important;
}

::v-deep.el-dropdown-menu__item.is-disabled {
  color: #bbb !important;
}

.delToRe_info {
  padding: 8px 10px;
  color: #082aff;
  margin-bottom: 10px;
  background-color: #EBEEFF;
  border-radius: 8px;

}
</style>
